package com.task.core.service.impl;

import java.util.List;
import javax.annotation.Resource;

import com.task.common.enums.QuestionOperationTypeEnum;
import com.task.common.enums.QuestionPromptContentEnum;
import com.task.common.info.QuestionShowInfo;
import com.task.common.redis.RedisKeyConstants;
import com.task.core.domain.ProxyPlatformInfo;
import com.task.core.service.ProxyPlatformService;
import com.task.core.vo.resp.ProxyDetailRespVo;
import io.jsonwebtoken.lang.Collections;
import org.springframework.stereotype.Service;

import com.task.common.annotation.DataScope;
import com.task.common.core.redis.RedisCache;
import com.task.common.domain.info.KeyAndValue;
import com.task.common.enums.QuestionInfoTypeEnum;
import com.task.common.exception.ServiceException;
import com.task.common.info.PluginInfo;
import com.task.common.info.ProxyInfo;
import com.task.common.utils.SecurityUtils;
import com.task.common.utils.StringUtils;
import com.task.common.utils.uuid.UUID;
import com.task.core.dto.request.ProxyRequestDTO;
import com.task.core.dto.request.QuestionInfoRequestDTO;
import com.task.core.mapper.ProxyMapper;
import com.task.core.service.ProxyService;
import com.task.core.service.QuestionInfoService;

/**
 * @author 迪迦.
 * @date 2024/11/4 17:29
 */
@Service("ProxyService")
public class ProxyServiceImpl implements ProxyService {

  @Resource
  private ProxyMapper proxyMapper;

  @Resource
  private RedisCache redisService;

  @Resource
  private QuestionInfoService questionInfoService;

  @Resource
  private ProxyPlatformService proxyPlatformService;

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<ProxyInfo> getProxyByPage(ProxyRequestDTO request) {
    //request.setOperationBy(SecurityUtils.checkAdmin());
    List<ProxyInfo> proxyByPage = proxyMapper.getProxyByPage(request);
    for (ProxyInfo info : proxyByPage) {
      List<QuestionShowInfo> questionShowInfoList = questionInfoService.getQuestionInfosByTypeAndCode(QuestionInfoTypeEnum.PROXY.name(), info.getCode());
      questionShowInfoList.stream().
              forEach(f ->{
                if( QuestionOperationTypeEnum.DELETE.getCode().equals(f.getOperationType()) &&
                        QuestionInfoTypeEnum.PROXY.name().equals(f.getQuestionType()) ){
                  f.setShowContent(info.getProxyName()+","+QuestionPromptContentEnum.PROXY_DELETE_PROMPT_CONTENT.getMsg());
                }else{
                  f.setShowContent(info.getProxyName()+","+f.getShowContent());
                }
              });
      info.setQuestionInfos(questionShowInfoList);
    }
    return proxyByPage;
  }

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<KeyAndValue> getProxyForOption(ProxyRequestDTO request) {
    //request.setOperationBy(SecurityUtils.checkAdmin());
    return proxyMapper.getProxyForOption(request);
  }

  @Override
  public void addProxy(ProxyRequestDTO request) {
    if (StringUtils.isEmpty(request.getVersionCode())) {
      throw new ServiceException("版本编号不能为空");
    }
    if (StringUtils.isEmpty(request.getProxyPlatformCode())) {
      throw new ServiceException("关联上层code不能为空");
    }
    if (questionInfoService.checkVersionCode(QuestionInfoTypeEnum.PROXY, request.getProxyPlatformCode(), request.getVersionCode())) {
      throw new ServiceException("关联的上层信息已更新,重新获取数据后再提交");
    }
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    request.setCode(UUID.randomUUID().toString().replace("-", ""));
    proxyMapper.addProxy(request);
    ProxyPlatformInfo platformInfo = proxyPlatformService.getProxyPlatformById(request.getProxyPlatformCode());
    redisService.setCacheObject(RedisKeyConstants.PROXY_INFO.formatKey(request.getCode()), new ProxyInfo(request.getId(),request.getCode(), request.getProxyName(),
        request.getProxyPlatformCode(), request.getConfig(), request.getDescription(),platformInfo.getProxyPlatformName()));
  }

  @Override
  public void modifyProxy(ProxyRequestDTO request) {
    if (StringUtils.isEmpty(request.getVersionCode())) {
      throw new ServiceException("版本编号不能为空");
    }
    if (StringUtils.isEmpty(request.getProxyPlatformCode())) {
      throw new ServiceException("关联上层code不能为空");
    }
    if (questionInfoService.checkVersionCode(QuestionInfoTypeEnum.PROXY, request.getProxyPlatformCode(), request.getVersionCode())) {
      throw new ServiceException("关联的上层信息已更新,重新获取数据后再提交");
    }
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    Integer integer = proxyMapper.modifyProxy(request);
    if (integer == 0) {
      throw new ServiceException("code不存在");
    }
    ProxyInfo proxy = proxyMapper.getProxyByCode(request);
    ProxyPlatformInfo platformInfo = proxyPlatformService.getProxyPlatformById(request.getProxyPlatformCode());
    redisService.setCacheObject(RedisKeyConstants.PROXY_INFO.formatKey(request.getCode()), new ProxyInfo(proxy.getId(),request.getCode(), request.getProxyName(),
            request.getProxyPlatformCode(), request.getConfig(), request.getDescription(),platformInfo.getProxyPlatformName()));
    //查找是否存在已关联的修改过的上层数据
    List<QuestionShowInfo> questions = questionInfoService.getQuestionInfosByTypeAndCode(QuestionInfoTypeEnum.PROXY.name(), request.getCode());
    if(!Collections.isEmpty(questions)){
      questions.forEach(f ->{
        String key = RedisKeyConstants.QUESTION_FIX_INFO.formatKey(request.getCode(), f.getCode());
        if(!redisService.hasKey(key)){
          redisService.setCacheObject(key,true);
        }
      });
    }
//    questionInfoService.fixQuestion(new QuestionInfoRequestDTO(QuestionInfoTypeEnum.PROXY, request.getCode(), request.getOperationBy()));
  }

  @Override
  public void deleteProxy(String proxyCode, Long userId) {
    Integer integer = proxyMapper.deleteProxy(proxyCode, userId);
    if (integer == 0) {
      throw new ServiceException("code不存在");
    }
    //删除关联数据
    //删除和任务关联的数据
    proxyMapper.deleteMissionProxyRelation(proxyCode);
    redisService.deleteObject(RedisKeyConstants.PROXY_INFO.formatKey(proxyCode));
  }

  @Override
  @DataScope(deptAlias = "dept",userAlias = "su")
  public ProxyDetailRespVo getProxyDetailDetail(String proxyCode) {
    ProxyRequestDTO proxyRequestDTO = new ProxyRequestDTO();
    proxyRequestDTO.setCode(proxyCode);
    return proxyMapper.getDataSoucreDetail(proxyRequestDTO);
  }
}
